<template>
  <div id="users">
    <el-breadcrumb separator="/" class="nav_ul">
      <el-breadcrumb-item :to="{ path: './welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <div class="nav_content">
        <div class="seek_block">
          <el-input placeholder="请输入搜索内容" v-model="userQu.query" clearable @change="seekData"></el-input>
          <el-button icon="el-icon-search" circle @click="seekData"></el-button>
        </div>
        <el-button type="primary" class="nav_button" @click="userOn = true">添加用户</el-button>
      </div>
      <el-table :data="users" style="width: 100%" stripe border>
        <el-table-column label="id" width="80" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="create_time"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state" width="100px">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="stateChange(scope.row)">
          </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220px" align="center">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="userRoles(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="page_block"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userQu.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="userQu.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <el-dialog
      title="添加用户"
      :visible.sync="userOn"
      width="50%"
      :before-close="closeAddUser">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAddUser">取 消</el-button>
        <el-button type="primary" @click="addUserDate">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改用户"
      :visible.sync="editOn"
      width="50%"
      :before-close="closeeditUser">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeeditUser">取 消</el-button>
        <el-button type="primary" @click="editUserDate">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配角色"
      :visible.sync="userRolesOn"
      width="50%"
      :before-close="closeUserRole">
        <div>
          <p>当前用户名：{{userData.username}}</p>
          <p>当前的角色：{{userData.role_name}}</p>
          <p>分配新角色：
            <el-select v-model="newRoles" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </p>
        </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeUserRole">取 消</el-button>
        <el-button type="primary" @click="putUsersRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<style scoped>
  .nav_ul {margin-bottom:20px;}
  .seek_block button.el-button.is-circle {
      float: right;
      position: absolute;
      right: 0;
      top: 0;
      background: #f2f6f5;
      width: 62px;
      border-radius: 0;
      cursor: pointer;
  }

  .seek_block {
      width: 280px;
      padding-right:60px;
      position: relative;
      overflow: hidden;
      border-radius: 3px;
      float: left;
  }
  .nav_button {float: left;margin-left:30px;}
  .nav_content:after {content: "";display: block;clear: both;}
  .nav_content {margin-bottom:20px;}
  .page_block {margin-top:20px;}
</style>
<script>
export default {
  data () {
    // 验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      var emailTest = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (emailTest.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的邮箱'))
      }
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'))
      }
      var emailTest = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (emailTest.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的手机号'))
      }
    }
    return {
      userQu: {
        query: '', // 查询参数
        pagenum: 1, // 当前页
        pagesize: 5 // 总页数
      },
      users: [], // 用户数据列表
      total: 10, // 总记录数
      userOn: false, // 添加用户表单开关
      addForm: { // 添加用户请求数据
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: { // 添加用户的验证规则
        username: [
          { required: true, message: '请输入您的用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入您的密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur', required: true } // 自定义邮箱验证
        ],
        mobile: [
          { validator: checkMobile, trigger: 'blur', required: true } // 自定义手机号验证
        ]
      },
      editOn: false, // 修改用户表单开关
      editForm: { // 修改用户请求数据
        username: '',
        email: '',
        mobile: ''
      },
      editFormRules: { // 修改用户验证规则
        username: [
          { required: true, message: '请输入您的用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur', required: true } // 自定义邮箱验证
        ],
        mobile: [
          { validator: checkMobile, trigger: 'blur', required: true } // 自定义手机号验证
        ]
      },
      userRolesOn: false, // 分配角色开关
      userData: [], // 用户角色数据
      rolesList: [], // 所有角色的数据列表
      newRoles: '' // 新角色
    }
  },
  methods: {
    async getUserList () { // 获取用户列表
      const { data: res } = await this.$http.get('users?query=' + this.userQu.query + '&&pagenum=' + this.userQu.pagenum + '&&pagesize=' + this.userQu.pagesize)
      this.users = res.data.users
      this.total = res.data.total
    },
    handleSizeChange (val) { // 总页数
      this.userQu.pagesize = val
      this.getUserList()
    },
    handleCurrentChange (val) { // 当前页
      this.userQu.pagenum = val
      this.getUserList()
    },
    seekData () { // 数据搜索
      this.getUserList()
    },
    async stateChange (da) { // 状态变更
      const { data: res } = await this.$http.put('users/' + da.id + '/state/' + da.mg_state)
      if (res.meta.status !== 200) {
        da.mg_state = !da.mg_state // 状态变更失败需更正按钮状态
        return this.$message.error(res.meta.msg)
      } else { // 状态变更成功
        this.$message.success(res.meta.msg)
      }
    },
    closeAddUser () { // 关闭添加用户
      this.userOn = false
      this.addForm = {} // 清空表单列表
    },
    addUserDate () { // 添加用户表单
      this.$refs.addFormRef.validate(async (vaild) => { // 判断预验证是否通过
        if (vaild) { // 通过预验证
          const { data: res } = await this.$http.post('users', this.addForm)
          if (res.meta.status !== 201) { // 添加用户失败提示
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          this.closeAddUser() // 关闭添加窗口
          this.getUserList() // 刷新用户列表
        }
      })
    },
    async editUser (id) { // 根据 ID 查询用户信息
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editForm = res.data
      this.editOn = true
    },
    deleteUser (id) { // 根据 ID 删除单个用户
      this.$confirm('是否永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getUserList() // 刷新用户列表
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    closeeditUser () { // 关闭编辑用户
      this.editOn = false
      this.editForm = {} // 清空表单列表
    },
    editUserDate () { // 编辑用户表单
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.put('users/' + this.editForm.id, this.editForm)
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          this.closeeditUser() // 关闭添加窗口
          this.getUserList() // 刷新用户列表
        }
      })
    },
    // 用户角色分配
    async userRoles (data) {
      this.userRolesOn = true
      this.userData = data
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.rolesList = res.data
    },
    // 关闭用户角色分配
    closeUserRole () {
      this.userRolesOn = false
      this.newRoles = ''
    },
    async putUsersRole () {
      const { data: res } = await this.$http.put('users/' + this.userData.id + '/role', { rid: this.newRoles })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.closeUserRole()
      this.getUserList()
    }
  },
  mounted: function () {
    this.getUserList() // 执行获取用户列表
  }
}
</script>
